﻿using IdentityServer4.Models;
using IdentityServer4.SqlSugarCore.DbContexts;
using IdentityServer4.SqlSugarCore.Interfaces;
using IdentityServer4.SqlSugarCore.Mappers;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdentityServer4.SqlSugarCore
{
    public class ClientStore : IClientStore
    {
        private readonly ILogger<ClientStore> _logger;
        private readonly ISqlSugarClient _db;

        public ClientStore(ILogger<ClientStore> logger, DbContext dbContext)
        {
            _logger = logger;
            _db = dbContext.Db;
        }

        /// <summary>
        /// 根据客户端ID 获取客户端信息内容
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public async Task<Client> FindClientByIdAsync(string clientId)
        {
            var cModel = new Client();
            var _client = new Entities.Client();
           
            _client = await _db.Queryable<Entities.Client>()
                .Where(x => x.ClientId == clientId)
                .Mapper(x => x.AllowedCorsOrigins, x => x.AllowedCorsOrigins.First().Id)
                .Mapper(x => x.AllowedGrantTypes, x => x.AllowedGrantTypes.First().Id)
                .Mapper(x => x.AllowedScopes, x => x.AllowedScopes.First().Id)
                .Mapper(x => x.Claims, x => x.Claims.First().Id)
                .Mapper(x => x.ClientSecrets, x => x.ClientSecrets.First().Id)
                .Mapper(x => x.IdentityProviderRestrictions, x => x.IdentityProviderRestrictions.First().Id)
                .Mapper(x => x.PostLogoutRedirectUris, x => x.PostLogoutRedirectUris.First().Id)
                .Mapper(x => x.Properties, x => x.Properties.First().Id)
                .Mapper(x => x.RedirectUris, x => x.RedirectUris.First().Id)
                .SingleAsync();
            cModel = _client.ToModel();

            _logger.LogDebug("{clientId} found in database: {clientIdFound}", clientId, _client != null);

            return cModel;
        }
    }
}

